﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

using ExpenseTracker.Platform;
using ChartForm;

namespace Expense_Tracker
{
    public partial class Form1 : Form
    {
        #region Data Members --------------------

        private int initialYear;
        private int rangeOfYears;

        private int DEFAULT_INITIAL_YEAR = 2012;
        private int DEFAULT_RANGE_OF_YEARS = 5;

        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        #region methods -------------------------

        private void getDataButton_Click(object sender, EventArgs e)
        {
            clearButton.PerformClick();

            int selectedIndex = monthList.SelectedIndex;
            
            if (selectedIndex == -1 || yearList.SelectedItem == null)
            {
                MessageBox.Show("No month and/or year selected. Please select a month as well as year to retrieve data for.", 
                    "Error Getting Data", MessageBoxButtons.OK);
                return;
            }

            int selectedYear = (int)yearList.SelectedItem;
            SqlServerDataHandler newDataHandler = new SqlServerDataHandler();
            DataTable resultTable = newDataHandler.GetData(selectedIndex, selectedYear);
            dataGridView1.DataSource = resultTable;
            dataGridView1.Columns[0].Visible = false;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            
            //Add custom Drop-down list for ExpenseType column
            dataGridView1.Columns.Remove("Type");
            DataGridViewComboBoxColumn expenseTypeColumn = new DataGridViewComboBoxColumn();
            expenseTypeColumn.DataSource = SqlServerDataHandler.GetExpenseTypes();
            expenseTypeColumn.Name = "ExpenseType";
            expenseTypeColumn.ValueMember = "type";
            expenseTypeColumn.DisplayMember = "Type";
            expenseTypeColumn.DataPropertyName = "Type";
            dataGridView1.Columns.Insert(2, expenseTypeColumn);

            //Add custom calendar control for Date column
            /*CalendarColumn dateColumn = new CalendarColumn();
            dateColumn.Name = "Date";
            dataGridView1.Columns.Remove("Date");
            dataGridView1.Columns.Insert(3, dateColumn);*/
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            List<ExpenseEntry> expenseEntriesToSave = new List<ExpenseEntry>();
            int count = 0;
            for (count = 0; count < dataGridView1.RowCount; count++)
            {
                if (dataGridView1.Rows[count].Cells[0].Value == DBNull.Value)
                {
                    //Set to an invalid int value to prevent exception due to conversion below
                    //the id will be autogenerated while entering into the database
                    dataGridView1.Rows[count].Cells[0].Value = -1;
                }

                //skip rows with empty amount entry
                //TODO: skip only if all items in the row are empty, else if only some are empty then
                //      display error
                if (dataGridView1.Rows[count].Cells[1].Value == null)
                {
                    continue;
                }
                ExpenseEntry newExpense = new ExpenseEntry();
                newExpense.Id = Convert.ToInt32(dataGridView1.Rows[count].Cells[0].Value);
                newExpense.Amount = Convert.ToDouble(dataGridView1.Rows[count].Cells[1].Value);
                newExpense.ExpenseType = SqlServerDataHandler.GetExpenseId((string)dataGridView1.Rows[count].Cells[2].Value);
                newExpense.Date = Convert.ToDateTime(dataGridView1.Rows[count].Cells[3].Value.ToString());
                newExpense.Comment = dataGridView1.Rows[count].Cells[4].Value.ToString();

                expenseEntriesToSave.Add(newExpense);               
            }

            SqlServerDataHandler newDataHandler = new SqlServerDataHandler();
            if (!newDataHandler.InsertData(expenseEntriesToSave))
            {
                MessageBox.Show("Problem encountered while saving data. Please contact the blockhead who wrote this program",
                    "Error Saving data", MessageBoxButtons.OK);
            }
            //refresh data in Gridview
            getDataButton.PerformClick();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            if (dataGridView1.Columns.Count != 0)
            {
                dataGridView1.Columns.Remove("ExpenseType");
            }            
        }

        private void chartButton_Click(object sender, EventArgs e)
        {
            Dictionary<string, Double> chartData = new Dictionary<string, double>();
            Double sum = 0;
            for (int rowCount = 0; rowCount < dataGridView1.RowCount; rowCount++)
            {
                sum += Convert.ToDouble(dataGridView1.Rows[rowCount].Cells[1].Value);
            }
            //To skip the last empty line in the table, use RowCount-1
            for (int rowCount = 0; rowCount < dataGridView1.RowCount-1; rowCount++)
            {
                Double totalExpensePerType = Convert.ToDouble(dataGridView1.Rows[rowCount].Cells[1].Value);
                string expenseType = (string)dataGridView1.Rows[rowCount].Cells[2].Value;
                Double retrievedTotalExpensePerType;
                if (chartData.TryGetValue(expenseType, out retrievedTotalExpensePerType))
                {
                    //LOG MSG: data already exists for the key. Add the new data
                    chartData.Remove(expenseType);
                    chartData.Add(expenseType, totalExpensePerType + retrievedTotalExpensePerType);
                }
                else
                {
                    chartData.Add(expenseType, totalExpensePerType);
                }                
            }
            chartForm newChart = new chartForm(chartData, monthList.SelectedIndex, sum);
            newChart.Show();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                initialYear = Convert.ToInt32(ConfigurationManager.AppSettings["initialYear"]);
                rangeOfYears = Convert.ToInt32(ConfigurationManager.AppSettings["rangeOfYears"]);
            }
            catch (Exception ex)
            {
                // exception encountered
                initialYear = DEFAULT_INITIAL_YEAR;
                rangeOfYears = DEFAULT_RANGE_OF_YEARS;
            }
            for (int i = initialYear; i < (initialYear + rangeOfYears); i++)
            {
                yearList.Items.Add(i);
            }
        }

        #endregion
    }
}
